package br.edu.ufcg.greengrid.event.reader;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

import br.edu.ufcg.greengrid.event.Event;

public class EventReaderTest {

	private File file;

	@Before
	public void setUp() throws Exception {
		this.file = File.createTempFile("test-prefix", "suffix");
	}

	@After
	public void tearDown() throws Exception {
		assertTrue(this.file.delete());
	}

	@SuppressWarnings("serial")
	@Test
	public void testReadEvents() throws IOException {

		MyEventReader reader = new MyEventReader();
		
		writeContent("1\n2\n3", file);

		List<MyEvent> expected = new ArrayList<MyEvent>(3) {
			{
				add(new MyEvent(1));
				add(new MyEvent(2));
				add(new MyEvent(3));
			}
		};
		List<MyEvent> actual = reader.read(file);

		assertEquals(expected.size(), actual.size());
		for (int i = 0; i < expected.size(); i++) {
			assertEquals(expected.get(i), actual.get(i));
		}
	}

	private void writeContent(String content, File file) throws IOException {
		BufferedWriter bw = null;

		try {

			bw = new BufferedWriter(new FileWriter((file)));
			bw.write(content);

		} finally {
			if (bw != null) {
				bw.close();
			}
		}
	}

	private static class MyEventReader extends EventReader<MyEvent> {

		@Override
		protected MyEvent getEvent(String line) {
			return new MyEvent(Integer.parseInt(line));
		}

	}

	private static class MyEvent extends Event {

		private int id;

		public MyEvent(int id) {
			super();
			this.id = id;
		}

		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + id;
			return result;
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			MyEvent other = (MyEvent) obj;
			if (id != other.id)
				return false;
			return true;
		}

	}

}
